#!/usr/bin/env python
#
#   Changes:
#   - example of usage TreeWalker moved to examples/treewalker1.py
#
__doc__ = ''' Python Flow Control Library, TreeWalker Processes '''
__author__ = 'Andrey Usov <http://devel.ownport.net>'
__all__ = ['TreeWalker',]


import os
from pyflowctrl.core4 import WAITING, PROCESSING
from pyflowctrl.core4 import EmptyStream, Stream, Process, Packet

class TreeWalker(Process):
    ''' Tree Walker '''
    __PROCESS__ = {
                    'name': 'TreeWalker',
                    'description': 'Walk through directory tree and return directiories and files',
                    'author': 'Andrey Usov <http://devel.ownport.net>',
                    'url': 'http://pyflowctrl.googlecode.com/hg/pyflowctrl/core4/processes/treewalker2.py',
                    'io': {'input': {}, 'output': {}, },
                }
        
    def __walktree(self, top):
        """ Directory walker """
        try:
            names = os.listdir(top)
        except OSError:
            names = []
        for name in names:
            if os.path.isdir(os.path.join(top, name)):
                for (newtop, children) in self.__walktree(os.path.join(top, name)):
                    yield newtop, children
        yield top, names

    def main(self):
        while True:
            try:
                packet = self.io['input'].get()
            except EmptyStream:
                yield WAITING
                continue
                
            if not os.path.exists(packet.path):
                raise IOError("%s does not exist" % packet.path)
            self.io['output'].put(packet)
            for path, names in self.__walktree(packet.path):
                for name in names:
                    packet.path = os.path.join(path, name)
                    self.io['output'].put(packet)
                    yield PROCESSING

    
